import { Text, StyleSheet, View, TextInput, ActivityIndicator, TouchableOpacity } from 'react-native'
import React, { useState } from 'react'
import { connect } from 'react-redux'
import { pTx } from '../../utils/dimensions';
import { importMnemonic, signMessage } from 'react-native-web3-wallet';
import { Toast } from '@ant-design/react-native'
import ShadowCard from "../../utils/shadowCard"
import LinearGradient from 'react-native-linear-gradient';
import httpApi from "../../api"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"


const ImportMnemonic = (props) => {
    const { NetworkList } = props
    const chainId = props.route.params.network
    const realm = useRealm();
    const wallets = useQuery(schemaName.Wallet)
    const walletList = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered(`chainId == ${chainId}  and state == 1`);
    })
    const [name] = useState(NetworkList.find(item => item.chainId == chainId).ticker + '-' + (walletList.length + 1))
    const [mnemonic, setMnemonic] = useState('')
    const [password, setPassword] = useState("")
    const [nameEnter, setNameEnter] = useState()
    const [loading, setLoading] = useState()

    const FinishCreateWallet = async () => {
        if (!mnemonic || !password) return
        try {
            setLoading(true)
            const res = await importMnemonic(mnemonic, password)
            const { address, keystore } = res
            const wallet = walletList.find(item => item.address == address)
            if (wallet) {
                setLoading(false)
                Toast.info('钱包已存在')
                return
            }
            const sign = await signMessage(
                JSON.stringify(res.keystore),
                password,
                httpApi.message,
            )
            const login = await httpApi.login({
                signature: sign,
                message: httpApi.message
            })
            const _id = new Realm.BSON.UUID()
            if (login.code == 20) {
                realm.write(() => {
                    realm.create(schemaName.UserInfo, { ...login.data.UserInfo, Token: login.data.Token }, true);
                    for (const wallet of wallets) {
                        wallet.current = false
                    }
                    realm.create(schemaName.Wallet, {
                        _id,
                        address,
                        keystore: JSON.stringify(keystore),
                        type: 1,
                        name: nameEnter || name,
                        state: 1,
                        chainId,
                        current: true,
                        symbol: NetworkList.find(item => item.chainId == chainId).ticker
                    }, true);
                });
            } else {
                const register = await httpApi.register({
                    nickname: nameEnter || name,
                    signature: sign,
                    message: httpApi.message,
                    profilePhoto: httpApi.defaultAvatar
                })
                if (register.code == 20) {
                    realm.write(() => {
                        realm.create(schemaName.UserInfo, { ...register.data.UserInfo, Token: register.data.Token }, true);
                        for (const wallet of wallets) {
                            wallet.current = false
                        }
                        realm.create(schemaName.Wallet, {
                            _id,
                            address,
                            keystore: JSON.stringify(keystore),
                            type: 1,
                            name: nameEnter || name,
                            state: 1,
                            chainId,
                            current: true,
                            symbol: NetworkList.find(item => item.chainId == chainId).ticker
                        }, true);
                    });
                }
            }
            props.navigation.navigate('wallet')
        } catch (error) {
            Toast.info(error)
        }
        setLoading(false)
    }

    return (
        <>
            <View style={styles.page}>
                <TextInput style={styles.textareaItem} numberOfLines={4} multiline={true} placeholder="请按顺序输入助记词，并使用空格分隔"
                    onChangeText={(value) => setMnemonic(value)} />
                <View style={styles.row}>
                    <Text style={styles.name}>密码 {name}</Text>
                    <TextInput
                        onChangeText={(value) => setPassword(value)}
                        style={styles.textareaItem}
                    >
                    </TextInput>
                </View>
                <View style={styles.row}>
                    <Text style={styles.name}>钱包名称</Text>
                    <TextInput
                        placeholder={name}
                        maxLength={15}
                        onChangeText={(value) => setNameEnter(value)}
                        style={styles.textareaItem}
                    >
                    </TextInput>
                </View>
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={[styles.linearGradient]}>
                        <TouchableOpacity type="primary" disabled={loading} style={[styles.button]} onPress={FinishCreateWallet}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>导入钱包</Text>
                            </>

                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
        </>
    )
}

const mapStateToProps = state => state.wallet

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(ImportMnemonic)

const styles = StyleSheet.create({
    page: {
        flex: 1,
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(20),
    },
    textareaItem: {
        backgroundColor: "#F7F7F7",
        borderRadius: pTx(6),
        borderColor: "#F7F7F7",
        borderWidth: 0,
        fontSize: pTx(16),
        textAlignVertical: 'top',
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
    },
    name: {
        fontSize: pTx(13),
        paddingTop: pTx(12),
        paddingBottom: pTx(8),
        color: "#0A0C14"
    },
    footerButton: {
        paddingTop: pTx(15),
        paddingBottom: pTx(63),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 6
    },
    button: {
        width: pTx(345),
        height: pTx(55),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    }
})